package com.frank.jpaSpecification.specification;

import com.frank.jpaSpecification.entity.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;

import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;

/**
 * @author 小石潭记
 * @date 2020/12/12 14:27
 * @Description: ${todo}
 */
@Component
public class StudentSpecification {

    /**
     * root 就是mobile实例  root.get("name") name是属性名 不是数据库字段名
     * @param paramRequest
     * @return
     * */
    public Specification<Student1> getStudentSpecification(PageStudentRequest paramRequest) {
        return (root, criteriaQuery, criteriaBuilder) -> {
            // http://localhost:8080/student?companyName=北京&pageNumber=0&pageSize=5&name=明
            /*
            // 普通的or
            Predicate namePre = criteriaBuilder.like(root.get("name"), "%" + paramRequest.getName() + "%");
            Predicate companyPre = criteriaBuilder.like(root.get("teacher").get("name"), "%" + paramRequest.getCompanyName() + "%");
            return criteriaBuilder.or(namePre, companyPre);
            */

            // 使用左连接查询
            Join<Student1, Company> companyJoin = root.join("company", JoinType.LEFT);

            Predicate namePre = criteriaBuilder.like(root.get("name"), "%" + paramRequest.getName() + "%");
            Predicate companyPre = criteriaBuilder.like(companyJoin.get("name"), "%" + paramRequest.getCompanyName() + "%");

            return criteriaBuilder.or(namePre, companyPre);

        };
    }

}
